package com.common.android.utils;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcelable;

/**
 * 应用相关的处理类
 * <br>Created 2014-8-20 下午9:08:55
 * @version  1.0
 * @author   luojw		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 *
 */
public class AppUtils {

    private static final String HAS_CREATE_SHORTCUT = "hasCreateShortCut";
    private static final int MIN_SDK_VERSION = 8;
    
    /**
     * 应用是否运行在后台
     * 
     * <br>Created 2014-10-9 下午5:05:52
     * @param context context
     * @return 在后台运行返回true，否则返回false
     * @author       cb
     */
    public static boolean  isBackgroundRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        if (activityManager == null) {
            return false;
        }
        // get running application processes
        List<ActivityManager.RunningAppProcessInfo> processList = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo process : processList) {
            if (process.processName.startsWith(context.getPackageName())) {
                boolean isBackground = process.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        && process.importance != RunningAppProcessInfo.IMPORTANCE_VISIBLE;
                return isBackground;
            }
        }
        return false;
    }
    
    /**
     * 获取应用的版本号
     * <br>Created 2014-8-20 下午9:22:41
     * @param context 上下文
     * @return versionName 应用的公开版本号
     * @author       huangyx
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        android.content.pm.PackageManager pm = context.getPackageManager();
        android.content.pm.PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
    
    /**
     * 获取应用的版本
     * <br>Created 2014-8-20 下午9:22:41
     * @param context 上下文  
     * @return versionCode 应用的内部版本号
     * @author       huangyx
     */
    public static int getAppVersionCode(Context context) {
        int versionCode = 0;
        android.content.pm.PackageManager pm = context.getPackageManager();
        android.content.pm.PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    
    /**
     * 创建应用快捷方式
     * <br>Created 2014-4-8下午5:33:46
     * @param act 应用的Activity
     * @param iconResId 应用图标id
     * @param appnameResId 应用名id
     * @author       huangszh
     */
    public static void createShortCut(Activity act, int iconResId,
            int appnameResId) {
        createShortCut(act, iconResId,act.getString(appnameResId));
    }
    
    /**
     * 创建应用快捷方式
     * 
     * <br>Created 2014-10-21 下午4:50:36
     * @param act 应用的Activity
     * @param iconResId 应用图标id
     * @param appname 应用名
     * @author       huangyx
     */
    public static void createShortCut(Activity act, int iconResId,
            String appname) {
        SharedPreferences sp = act.getPreferences(0);
        // 如果已经创建过了，直接赋值
        if(hasShortcut(act,appname)){
            sp.edit().putBoolean(HAS_CREATE_SHORTCUT, true).commit();
            return;
        }
        boolean hasCreat = sp.getBoolean(HAS_CREATE_SHORTCUT, false);
        if (!hasCreat) {
            Intent shortcutintent = new Intent(
                    "com.android.launcher.action.INSTALL_SHORTCUT");
            // 不允许重复创建
            shortcutintent.putExtra("duplicate", false);
            // 需要现实的名称
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                    appname);
            // 快捷图片
            Parcelable icon = Intent.ShortcutIconResource.fromContext(
                    act.getApplicationContext(), iconResId);
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
            // 点击快捷图片，运行的程序主入口
            Intent main = new Intent(Intent.ACTION_MAIN);
            main.addCategory(Intent.CATEGORY_LAUNCHER);
            main.setClass(act, act.getClass());
            shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,main);
            // 发送广播
            act.sendBroadcast(shortcutintent);
            sp.edit().putBoolean(HAS_CREATE_SHORTCUT, true).commit();
        }
    }
    
    /**
     * 判断是否存在快捷方式
     * <br>Created 2014-4-8下午5:39:40
     * @param activity 应用的activity
     * @param shortcutName 快捷方式名字
     * @return 应用存在快捷方式返回true，否则返回false
     * @author       huangszh
     */
    public static boolean hasShortcut(Activity activity, String shortcutName) { 
        String url = ""; 
        int sdkVersion = android.os.Build.VERSION.SDK_INT; 
        if(sdkVersion < MIN_SDK_VERSION){ 
            url = "content://com.android.launcher.settings/favorites?notify=true"; 
        }else{ 
            url = "content://com.android.launcher2.settings/favorites?notify=true"; 
        } 
        ContentResolver resolver = activity.getContentResolver(); 
        Cursor cursor = resolver.query(Uri.parse(url), null, "title=?",new String[] {shortcutName}, null); 
        if (cursor != null && cursor.moveToFirst()) { 
            cursor.close(); 
            return true; 
        } 
        return false; 
    } 
    
    /**
     * 简单判断当前手机是否有ROOT权限
     * <br>Created 2014-1-26下午11:43:33
     * @return 有ROOT权限返回true，否则返回false
     * @author       HuangYK
     */
    public static boolean isRoot() {
        boolean bool = false;

        try {
            if (new File("/system").canRead()
                    && (!new File("/system/bin/su").exists())
                    && (!new File("/system/xbin/su").exists())) {
                bool = false;
            } else {
                bool = true;
            }
        } catch (Exception e) {
               e.printStackTrace();
        }
        return bool;
    }
}
